﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.IO;
using System.Diagnostics;

namespace Lipesin.Wrapper
{

	class Launcher
	{
		private const string _namespace = "Lipesin.Wrapper.Content.";
		[STAThread]
		static void Main(string[] args)
		{
			//Assembly assembly = Assembly.GetCallingAssembly();
			Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();

			Dictionary<string, List<string>> files = GetEmbeddedFiles();
			string binPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
			if (!Directory.Exists(binPath)) Directory.CreateDirectory(binPath);

			try
			{
				foreach (KeyValuePair<string, List<string>> folder in files)
				{
					string dirPath = Path.Combine(binPath, folder.Key);
					if (!Directory.Exists(dirPath)) Directory.CreateDirectory(dirPath);
					foreach (string resourceName in folder.Value)
					{
						using (Stream embed = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
						using (Stream file = new FileStream(Path.Combine(dirPath, resourceName.Substring(_namespace.Length + folder.Key.Length)), FileMode.Create))
							embed.CopyTo(file);
					}
				}
				string sargs = null;
				if (args.Length > 0) sargs = args.Aggregate((s1, s2) => s1 + " " + s2);
				//ProcessStartInfo si = new ProcessStartInfo(Path.Combine(binPath, "Main.exe"), sargs);
				//si.WorkingDirectory = Directory.GetCurrentDirectory();
				//si.UseShellExecute = true;
				//si.
				//si.Verb = "test";

				System.Diagnostics.Process process;
				//process = Process.Start(si);
				string startPath = Path.Combine(binPath, "Main.exe");
				if (!File.Exists(startPath))
				{
					string[] exes = Directory.GetFiles(binPath, "*.exe");
					if (exes.Length != 1)
					{
						System.Windows.Forms.MessageBox.Show("Не найден файл для запуска.", null, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
						return;
					}
					startPath = exes[0];
				}
				process = Process.Start(startPath, sargs);
				process.WaitForExit();
			}
			finally
			{
				try { Directory.Delete(binPath, true); }
				catch { }
			}
		}
		private static Dictionary<string, List<string>> GetEmbeddedFiles()
		{
			Dictionary<string, List<string>> result = new Dictionary<string, List<string>>();
			string subdirs;
			using (Stream embed = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("Lipesin.Wrapper.DirStruct.txt"))
			using (StreamReader reader = new StreamReader(embed))
				subdirs = reader.ReadToEnd();
			Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
			List<string> root = new List<string>(assembly.GetManifestResourceNames());
			foreach (string dir in subdirs.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries).OrderByDescending(s => s.Length))
			{
				List<string> subdir = new List<string>();
				foreach (string file in root.ToArray())
					if (file.StartsWith(_namespace + dir.Replace("\\", ".") + "."))
					{
						subdir.Add(file);
						root.Remove(file);
					}
				result.Add(dir + "\\", subdir);
			}
			result.Add("", root.FindAll((s) => s.StartsWith(_namespace)));
			return result;
		}
	}
}
